#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/1/19 14:04
# @Author  : Seven
# @File    : 3-histogramDemo.py
# @Software: PyCharm
# function : 首先计算灰度直方图，进一步使用大津算法进行分割，并比较分析分割结果。

import cv2
import matplotlib.pyplot as plt


def histData(img, name):
    """
    计算灰度直方图
    :param name:
    :param img:
    :return:
    """
    # 参数：图片原数据：[img]、通道数：[0]、掩码图像：None、
    # 直方图每一维的条目个数的数组：[256]、每一维的像素值的范围：[0.0, 255.0]
    grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    grayHist = cv2.calcHist([grayImage],
                            [0],
                            None,
                            [256],
                            [0.0, 255.0])
    plt.title(name)
    plt.hist(grayHist)
    plt.show()


def ThresholdImage(image, name):
    """
    大津算法分割
    :param name:
    :param image:
    :return:
    """
    img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 阈值设置为125，最大阈值设置为255
    _, thresholdImage = cv2.threshold(img, 125, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    cv2.imshow("threshold-%s" % name, thresholdImage)


if __name__ == '__main__':
    pic2 = cv2.imread('image/pic2.png')
    pic6 = cv2.imread('image/pic6.png')
    # 计算灰度直方图
    histData(pic2, 'pic2')
    histData(pic6, 'pic6')
    # 大津算法
    ThresholdImage(pic2, 'pic2')
    ThresholdImage(pic6, 'pic6')

    cv2.waitKey(0)

# 灰度值分布比较开的图片，用大津算法更容易的分割。
